import { isEqual } from '@/common/plugins/tools/type'

export default {
  props: {},
  data() {
    return {
      datumRepayListTableName: 'datum_repay_list',
      datumRepayList: [],
      datumRepayListExists: [],
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    async getDatumRepayList(relatedId) {
      const [res] = await this.$utils.promise(
        this.$api.getData(
          this.$serviceName,
          this.datumRepayListTableName,
          {
            'customer_related_id.eq': relatedId,
          },
          { pay_time: 'asc' }
        )
      )

      this.datumRepayListExists = (res && res.data) || []
      this.datumRepayList = this.datumRepayListExists.map(item => ({ ...item }))
    },

    async updateDatumRepayListById(id, data) {
      await this.$api.updateData(this.$serviceName, this.datumRepayListTableName, id, data)
    },

    async updateDatumRepayListByIndex(index) {
      const changeItem = this.datumRepayList[index]
      const existItem = this.datumRepayListExists[index]

      if (isEqual(changeItem, existItem)) return

      const { datum_repay_list_id: id, ...data } = changeItem
      return this.$api
        .updateData(this.$serviceName, this.datumRepayListTableName, id, data)
        .then(res => {
          this.datumRepayListExists[index] = { ...changeItem }
          return res
        })
    },

    async putDatumRepayList(data) {
      await this.$api.updateBatch(this.$serviceName, this.datumRepayListTableName, data)
    },

    async deleteDatumRepayListById(id, relatedId) {
      await this.$utils
        .msgbox({
          message: `确定删除?`,
          type: 'warning',
          beforeClose: () =>
            this.$api.deleteData(this.$serviceName, this.datumRepayListTableName, id),
        })
        .then(() => {
          this.$message.success('删除成功！')
          return this.getDatumRepayList(relatedId)
        })
        .catch(() => this.$message.error(`删除失败，请重试！`))
    },
  },
}
